package cn.amossun.starter.api.data.security.aspect;

/**
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020/03/18 18:06
 **/
import cn.amossun.starter.api.data.security.rewrite.DecryptObjectRewriter;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.util.*;

/**
 * 脱敏拦截器
 *
 * @since 2021/8/16
 **/
@Slf4j
@Aspect
@AllArgsConstructor
public class DataSecurityAspect {

    private final DecryptObjectRewriter decryptObjectRewriter;

    @Pointcut("@annotation(cn.amossun.starter.common.annotation.ApiDataSecurity) && !within(cn.amossun.starter.common.annotation.AuthApiDataSecurity)")
    public void pointcutAnnotation(){}

    /**
     * 脱敏处理
     */
    @AfterReturning(pointcut="pointcutAnnotation()", returning="returnValue")
    public void doProcessAnnotation(JoinPoint joinPoint, Object returnValue) throws Throwable {
        doProcess(joinPoint, returnValue);
    }

    /**
     * 注解统一拦截器
     */
    protected Object doProcess(JoinPoint joinPoint, Object returnValue) throws Throwable {
        if(log.isDebugEnabled()) {
            log.debug("@AfterReturning：目标方法为：" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.debug("@AfterReturning：参数为：" + Arrays.toString(joinPoint.getArgs()));
            log.debug("@AfterReturning：返回值为：" + returnValue);
            log.debug("@AfterReturning：切入目标对象为：" + joinPoint.getTarget());
        }
        if (returnValue == null || decryptObjectRewriter.isPrimitive(returnValue.getClass())) {
            return returnValue;
        }
        decryptObjectRewriter.rewriter(returnValue);
        return returnValue;
    }

}
